package com.chooseCourses.servlet.admin;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;

@WebServlet("/CourseEdit")

public class CourseEdit extends HttpServlet {
    public CourseEdit() {super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String editId = req.getParameter("editId");
        String userName = req.getParameter("userName");
        int userId = Integer.parseInt(req.getParameter("userId"));
        String courseId = req.getParameter("courseId");
        String name = req.getParameter("name");
        String room = req.getParameter("room");

        //创建db对象
        BaseDao baseDao = new BaseDao();
        PreparedStatement ps = null;

        //创建更新sql语句
        String sql = "update course set id=?,name=?,room=? where id = ?";
        //调用更新操作
        //要更新的数据
        try {
            ps = baseDao.getConnection().prepareStatement(sql);
            ps.setString(1, courseId);
            ps.setString(2, name);
            ps.setString(3, room);
            ps.setString(4, editId);


            ps.executeUpdate();//执行更新
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            baseDao.closeResource(null,ps,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //成功返回管理员信息页面,这里可以设置一个提示页面再跳,不设置也可以
        PrintWriter out = resp.getWriter();
        resp.sendRedirect("admin/courseMes.jsp?userName=" + userName + "&userId=" + userId);

        doGet(req, resp);
    }
}
